package cn.wolfcode.luowowo.search.service.impl;

import cn.wolfcode.luowowo.search.dao.IUserInfoSearchDAO;
import cn.wolfcode.luowowo.search.query.SearchQueryObject;
import cn.wolfcode.luowowo.search.query.StrategySearchQuery;
import cn.wolfcode.luowowo.search.service.IUserInfoSearchService;
import cn.wolfcode.luowowo.search.template.UserInfoTemplate;
import com.alibaba.dubbo.config.annotation.Service;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.SearchQuery;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserInfoSearchServiceImpl implements IUserInfoSearchService {

    @Autowired
    private IUserInfoSearchDAO userInfoSearchDAO;


    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;



    @Override
    public void save(UserInfoTemplate template) {
        userInfoSearchDAO.save(template);
    }

    @Override
    public void update(UserInfoTemplate template) {
        userInfoSearchDAO.deleteById(template.getId());
        this.save(template);
    }

    @Override
    public void delete(Long id) {
        userInfoSearchDAO.deleteById(id);
    }

    @Override
    public UserInfoTemplate get(Long id) {
        return userInfoSearchDAO.findById(id).get();
    }

    @Override
    public List<UserInfoTemplate> list() {
        Iterable<UserInfoTemplate> all = userInfoSearchDAO.findAll();
        List<UserInfoTemplate> list = new ArrayList<>();
        all.forEach(cc -> list.add(cc));
        return list;
    }

    @Override
    public Page<UserInfoTemplate> query(SearchQuery qo) {
        
        
        Page<UserInfoTemplate> page = userInfoSearchDAO.findAll(qo.getPageable());
        return page;
    }


    @Override
    public void createIndex() {
        elasticsearchTemplate.createIndex(UserInfoTemplate.class);
        elasticsearchTemplate.putMapping(UserInfoTemplate.class);
    }




    @Override
    public Page<UserInfoTemplate> searchByDest(SearchQueryObject qo) {
        Page<UserInfoTemplate> page = Page.empty();
        try {
            page = userInfoSearchDAO.search(QueryBuilders.termQuery("destName", qo.getKeyword()), qo.getPageable());
        }catch (Exception e){
            e.printStackTrace();
        }


        return page;
    }

    public Page<UserInfoTemplate> queryUserByDestName(StrategySearchQuery qo) {
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        if (qo.getKeyword() != null) {
            boolQuery.must(QueryBuilders.termQuery("destName", qo.getKeyword()));
        }
        return userInfoSearchDAO.search(boolQuery,qo.getPageableWithSort());
    }
}
